<?php
/**
 * 功能描述：此接口用于发送短信内容到指定的手机
 * 短信供应商：点客
 * 
 * 作者：allen.qiang
 * 
 * Date: 2017/9/27
 */

namespace common\helps;

use Yii;
use backend\models\LogSms;

class api_sms_dianke{
    private $err_info = array(
        '0'=>'提交成功',
        '101'=>'无此用户',
        '102	密码错',
        '103'=>'提交过快（提交速度超过流速限制）',
        '104'=>'系统忙（因平台侧原因，暂时无法处理提交的短信）',
        '105'=>'敏感短信（短信内容包含敏感词）',
        '106'=>'消息长度错（>536或<=0）',
        '107'=>'包含错误的手机号码',
        '108'=>'手机号码个数错（群发>50000或<=0）',
        '109'=>'无发送额度（该用户可用短信数已使用完）',
        '110'=>'不在发送时间内',
        '111'=>'超出该账户当月发送额度限制',
        '112'=>'无此产品，用户没有订购该产品',
        '113'=>'extno格式错（非数字或者长度不对）',
        '115'=>'自动审核驳回',
        '116'=>'签名不合法，未带签名（用户必须带签名的前提下）'
    );
    /**
     *  add by zenan.li (FDG348) 20170905
     */
    public function sendSms($mobile ,$content){
        if (Yii::$app->params['sms_switch'] == 'off') {
            return true;
        }

        if ($content == '') {
            return false;
        }

        $task_id = 0;
        $fail_content = '';

        //设置选项，包括URL
        $apiUrl = Yii::$app->params['sms_dianke'] . "&mobile=" . $mobile ."&msg=" .urlencode ( $content ) ."&needstatus=true";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);

        $result = explode("\n", $output) ;
        $result_info = explode(",", $result[0]) ;
        if($result_info[1] == 0){
            $sms_status = 1;
            //成功
            //$result[1] 为 taskID
            $task_id = $result[1];
            error_log('短信发送成功：taskID=' . $result[1]   . $this->err_info[$result_info[1]]);
        }else{
            $sms_status = 2;
            //失败 CODE
            $fail_content = 'error_code = '. $result_info[1] . ' ' . $this->err_info[$result_info[1]];
            error_log('短信发送失败：' .$mobile . ' error_code = '. $result_info[1] . ' ' . $this->err_info[$result_info[1]]);
        }

        if (Yii::$app->params['sms_log_switch'] == 'on'){
                $logsms = new LogSms();
                $logsms->mobile = $mobile;
                $logsms->sms_content = $content;
                $logsms->sms_status = $sms_status;
                $logsms->ip = $_SERVER['REMOTE_ADDR'];
                if ($fail_content){
                    $logsms->fail_content = $fail_content;
                }
                $logsms->task_id = $task_id;
                $logsms->creator = $logsms->getCreator();
                $logsms->create_time = date('Y-m-d H:i:s',time());
                $logsms->insert();
            }

        return true;
    }
}